package com.whsxt.dao;

import com.whsxt.common.Constant;
import com.whsxt.common.PageInfo;
import com.whsxt.pojo.Customer;

import java.util.Date;
import java.util.Map;

/**
 * @Author 武汉尚学堂
 */
public class CustomerDao  extends BaseDao{

    public PageInfo<Customer> selectPage(Map<String, String> params, String page, String limit) {
       String sql = "select c.id,c.name,c.phone,c.sex,c.company,c.deleted,c.user_id as userId,c.create_time as createTime,c.delete_time as deleteTime,u.realname from customer c left join user u on c.user_id = u.id where 1=1 ";
        if (params.containsKey("name")){
            sql = sql + " and c.name like '%"+params.get("name")+"%' ";
        }
        if (params.containsKey("phone")){
            sql = sql + " and c.phone ="+params.get("phone");
        }
        if (params.containsKey("company")){
            sql = sql + " and c.company like '%"+params.get("company")+"%' ";
        }
        if (params.containsKey("userId")){
            sql = sql + " and c.user_id ="+params.get("userId");
        }
        PageInfo<Customer> customerPage = super.selectPage(sql,Customer.class,page,limit);
        return customerPage;
    }

    public Customer selectCustomerByPhone(String phone) {
        String sql = "select id from customer where phone = ?";
        return  super.selectOne(sql,Customer.class,phone);
    }

    public void insert(String name, String phone, String company, String sex, Integer userId) {
        String sql = "insert into customer (name,phone,company,sex,user_id) value(?,?,?,?,?)";
        super.executeUpdate(sql,name,phone,company,sex,userId);

    }

    public void updateById(String id, String name, String phone, String company, String sex) {
        String sql = "update customer set name = ?,phone=?,company=?,sex=? where id=?";
        super.executeUpdate(sql,name,phone,company,sex,id);
    }

    public void deleteById(String id) {
        String sql = "update customer set deleted = ?,delete_time = ? where id = ?";
        super.executeUpdate(sql, Constant.INVALID,new Date(),id);
    }

    public void batchUpdateCustomerUserId(String userId, String... customerIds) {
        String sql = "update customer set user_id = ? where id in( ";
        for (String customerId : customerIds) {
            sql = sql + customerId + ",";
        }
        sql = sql +"0)";//在后面拼接0  为了处理 最后的一个逗号
        super.executeUpdate(sql,userId);
    }
}
